package cn.mrcode.wxsdk.core.dialogue.common.helper;

import cn.mrcode.wxsdk.core.dialogue.common.util.CastUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Element;
import org.dom4j.Node;


/**
 * @author zhuqiang
 * @version V1.0
 * @date 2015/11/17 13:14
 */
public class Dom4jHelper {
    /**
     * 在root下根据xpth获取节点
     * @param root
     * @param xpathExpression
     * @return
     */
    public static Node selectSingleNode(Element root,String xpathExpression){
        if(root == null || StringUtils.isBlank(xpathExpression)){
            throw new RuntimeException(String.format("select SingleNode failure：xpathExpression=%s",xpathExpression));
        }
        return root.selectSingleNode(xpathExpression);
    }

    /**
     * 获取指定xpath下的节点的text文本
     * @param root
     * @param xpathExpression
     * @return 如果没有找到则返回null
     */
    public static String selectSingleNodeText(Element root,String xpathExpression){
        Node node = selectSingleNode(root, xpathExpression);
        return node == null?null:node.getText();
    }
    public static Node selectSingleNode(Node node,String xpathExpression){
        if(node == null || StringUtils.isBlank(xpathExpression)){
            throw new RuntimeException(String.format("select SingleNode failure：xpathExpression=%s",xpathExpression));
        }
        return node.selectSingleNode(xpathExpression);
    }

    /**
     * 在node下获取指定的attributeName
     * @param node
     * @param attName
     * @return
     */
    public static String getAttributeValue(Node node,String attName){
        if(node == null){
            throw new RuntimeException(String.format("get attributeValue failure:attName=%s",attName));
        }
       return  ((Element) node).attributeValue(attName);
    }

    public static boolean getAttributeValueBoolean(Node node,String attName,boolean defaultValue){
        String av = getAttributeValue(node, attName);
        boolean result = defaultValue;
        if(StringUtils.isNotBlank(av)){
            result = CastUtil.castBoolean(av);
        }
        return result;
    }

}
